<?php
namespace iBrand\Shop\Server\Http\Controllers;

use iBrand\Server\Http\Controllers\Controller;
use iBrand\Shop\Core\Models\Clerk;
use iBrand\Shop\Core\Models\Shop;
use iBrand\Server\Exception\UserExistsException;
use Illuminate\Auth\Events\Login;
use Illuminate\Http\Request;
use League\OAuth2\Server\Exception\OAuthServerException;
use RuntimeException;
use Validator;
use Hash;
use Image;
use iBrand\Shop\Core\Repositories\ShopOrderRepository;


class UploadController extends Controller
{
    protected  $shopOrderRepository;


    public function __construct(
        ShopOrderRepository $shopOrderRepository
    )
    {

    }

    public function index(Request $request)
    {

        $clerk= auth('clerk')->user();

        //TODO: 需要验证是否传入avatar_file 参数
        $file = $request->file('avatar_file');
        $Orientation = $request->input('Orientation');

        $destinationPath = storage_path('app/public/uploads');
        if (!is_dir($destinationPath)) {
            mkdir($destinationPath, 0777, true);
        }

        $extension = $file->getClientOriginalExtension();
        $filename = $this->generaterandomstring() . '.' . $extension;

        $image = $file->move($destinationPath, $filename);

        $img = Image::make($image);

        switch ($Orientation) {
            case 6://需要顺时针（向左）90度旋转
                $img->rotate(-90);
                break;
            case 8://需要逆时针（向右）90度旋转
                $img->rotate(90);
                break;
            case 3://需要180度旋转
                $img->rotate(180);
                break;
        }

        $img->resize(320, null, function ($constraint) {
            $constraint->aspectRatio();
        })->crop(320, 320, 0, 0)->save();

        return $this->api(['url' => url('/storage/uploads/' . $filename)]);
    }


    private function generaterandomstring($length = 10)
    {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }









}